<template>
  <div class="container">
    <van-nav-bar>
      <!--<van-icon size="20" name="arrow-left" slot="left" color="rgb(150, 151, 153)"/>-->
      <p slot="title" style="font-size: 14px">分类精选</p>
    </van-nav-bar>
    <van-search disabled placeholder="请输入商品名称" @click="searchHandler"/>
    <keep-alive>
      <div class="content">
        <van-sidebar v-model="activeKey" style="height: 100%;background-color: #F7F8FA">
          <van-sidebar-item @click="slideBarHandler" class="van-ellipsis" v-for="(item,index) in classify"
                            :key="index" :title="item"/>
        </van-sidebar>
        <div class="right">
          <div class="cardList" :class="{show:index===show}" v-for="(item,index) in classify"
               :key="index">
            <filter-bar @types="sortupHandler" :filter="shopMap[category].isFilter" :card="card"/>
            <van-row class="shop-list">
              <van-col :span="col" v-for="item in shopMap[category].store" :key="item.proid">
                <div style="padding: 5px" v-if="index===show">
                  <shop-card :shop-data="item" :types="types"></shop-card>
                </div>
              </van-col>
            </van-row>
            <van-empty v-if="shopMap[category].store.length===0" description="这里什么也没有"></van-empty>
          </div>
        </div>
      </div>
    </keep-alive>
    <van-popup v-model="filterVisable" closeable @click-overlay="cancelFilter" @click-close-icon="cancelFilter"
               position="right"
               :style="{ width: '90%',height:'100%' }">
      <div class="filterView">
        <b>价格区间(元)</b>
        <div class="input-view">
          <div class="input-block">
            <input v-model="lowerPrice" type="text" placeholder="最低价">
          </div>
          <div class="line"></div>
          <div class="input-block">
            <input v-model="higherPrice" type="text" placeholder="最高价">
          </div>
        </div>
        <b>品牌</b>
        <tab-check v-model="brandIndex" :option="brands"></tab-check>
        <b>分类</b>
        <tab-check v-model="classIndex" :option="classify"></tab-check>
        <van-button plain style="margin-top: 15px" type="warning" @click="doFilter">
          开启筛选
        </van-button>
        <van-button @click="doReset" style="margin-left: 5px">重置内容</van-button>
      </div>
    </van-popup>
  </div>
</template>

<script>
import Vue from 'vue'
import ShopCard from '../../components/shop/ShopCard'
import FilterBar from '../../components/shop/FilterBar'
import TabCheck from '../../components/shop/TabCheck'
import { Button, NavBar, Search, Tab, Tabs, Sidebar, SidebarItem, Grid, GridItem, Col, Row, Popup } from 'vant'
import { requestClassifyList } from '../../api/classify'
import { requestBrandList } from '../../api/brand'
import {
  requestShoplistByClassify,
  getShoplistOrderBySales,
  getShoplistOrderByDiscount,
  getShoplistOrderByPrice,
  getMultiFilterShoplist
} from '../../api/commodity'
import $throttle from '../../../public/js/speed'

Vue.use(Search)
Vue.use(Button)
Vue.use(NavBar)
Vue.use(Popup)
Vue.use(Tab)
Vue.use(Tabs)
Vue.use(Sidebar)
Vue.use(SidebarItem)
Vue.use(Grid)
Vue.use(GridItem)
Vue.use(Row)
Vue.use(Col)

export default {
  name: 'Keep',
  data () {
    return {
      activeKey: 0,
      show: 0,
      col: 12,
      types: 'shop-card',
      card: 0,
      once: true,
      filterVisable: false,
      shopMap: {},
      classify: [],
      category: '',
      brands: [],
      lowerPrice: '',
      higherPrice: '',
      brandIndex: 0,
      classIndex: 0
    }
  },
  created () {
    this.init()
  },
  activated () {
    if (document.querySelector('.cardList')) {
      document.querySelectorAll('.cardList').forEach((item, index) => {
        item.scrollTop = localStorage.getItem('scroller' + index) || 0
      })
    }
    window.dispatchEvent(new Event('resize'))
  },
  deactivated () {
    this.classify.forEach((item, index) => {
      if (this.activeKey !== index)
        localStorage.setItem('scroller' + index, 0)
    })
  },
  methods: {
    init () {
      requestClassifyList().then(res => {
        this.classify = ['全部商品', ...res.data]
        this.category = this.classify[0]
      })
      requestBrandList().then(res => {
        this.brands = ['全部品牌', ...res.data]
      })
    },
    slideBarHandler (value) {
      this.activeKey = value
      setTimeout(() => {
        this.category = this.classify[value]
        this.show = value
      }, 100)
    },
    searchHandler(){
      this.$router.push('/search')
    },
    cardHandler () {
      this.card = (this.card + 1) % 2
      if(this.card){
        this.col = 24
        this.types = 'shop-line'
      }else{
        this.col = 12
        this.types = 'shop-card'
      }
      console.log('视图切换')
    },
    cancelFilter () {
      this.filterVisable = false
      this.shopMap[this.category].isFilter = 0
    },
    filterHandler () {
      if (!this.shopMap[this.category].isFilter) {
        this.filterVisable = true
        this.shopMap[this.category].isFilter = 1
      } else {
        this.shopMap[this.category].nin.length = 0
        this.shopMap[this.category].store.length = 0
        this.shopMap[this.category].sort = false
        this.shopMap[this.category].isFilter = 0
        this.requestShopList(this.category, 'update')
      }
    },
    doFilter () {
      const brand = this.brands[this.brandIndex]
      const category = this.classify[this.classIndex]
      const lowerPrice = Number(this.lowerPrice)
      const higherPrice = Number(this.higherPrice)
      if(Number.isNaN(lowerPrice)||Number.isNaN(higherPrice)){
        this.$toast('输入的不是数字')
        return;
      }
      getMultiFilterShoplist({
        brand,
        category,
        lowerPrice,
        higherPrice
      }).then(res => {
        this.shopMap[this.category].store = res.data
        this.$forceUpdate()
      })
      this.filterVisable = false
      this.shopMap[this.category].isFilter = 1
      this.shopMap[this.category].sort = true
    },
    doReset () {
      this.brandIndex = -1
      this.classIndex = -1
      this.lowerPrice = ''
      this.higherPrice = ''
    },
    sortupHandler (fields, sort) {
      if (fields === 'filter') {
        // this.isFilter = 0
        this.filterHandler()
        return
      }
      if (fields === 'card') {
        this.cardHandler()
        return
      }
      if (!sort) {
        this.shopMap[this.category].nin.length = 0
        this.shopMap[this.category].store.length = 0
        this.shopMap[this.category].sort = false
        this.requestShopList(this.category, 'update')
        return
      }
      if (sort === 2) {
        sort = -1
      }
      this.requestSortList(fields, sort)
    },
    async requestSortList (field = 'sale', sortup = 1) {
      let res = {}
      this.shopMap[this.category].isFilter = 0
      switch (field) {
        case 'sale':
          res = await getShoplistOrderBySales(sortup, this.category)
          break
        case 'price':
          res = await getShoplistOrderByPrice(sortup, this.category)
          break
        case 'discount':
          res = await getShoplistOrderByDiscount(sortup, this.category)
          break
        default:
          console.error('拦截失败')
      }
      this.shopMap[this.category].store = res.data
      this.shopMap[this.category].nin = []
      this.shopMap[this.category].sort = true
      this.$forceUpdate()
    },
    requestShopList (type, mode = 'init') {
      const InitAndOnce = mode === 'init' && this.shopMap[this.category].once
      const Init = mode === 'init' && !this.shopMap[this.category].once
      const currentMap = this.shopMap[this.category]
      if (Init) {
        return
      }
      requestShoplistByClassify(type, currentMap.nin).then(res => {
        currentMap.store.push(...res.data)
        currentMap.nin.push(...res.data.map(item => item.proid))
        this.$forceUpdate()
        InitAndOnce ? currentMap.once = false : ''
        this.once ? this.scrollHandler() : ''
        this.once = false
      })
    },
    scrollHandler () {
      document.querySelectorAll('.cardList').forEach((item) => {
        item.addEventListener('scroll', () => {
          $throttle(() => {
            if (item.clientHeight + item.scrollTop >= item.scrollHeight - 5) {
              console.log('滚动到底部')
              !this.shopMap[this.category].sort ? this.requestShopList(this.category, 'update') : ''
            }
            localStorage.setItem('scroller' + this.activeKey, item.scrollTop)
          }, 300)
        })
      })
    },
  },
  watch: {
    category: function () {
      if (!this.shopMap[this.category]) {
        this.shopMap[this.category] = {
          nin: [],
          store: [],
          once: true,
          sort: false,
          isFilter: 0
        }
      }
      this.requestShopList(this.category, 'init')
    }
  },
  components: {
    ShopCard,
    FilterBar,
    TabCheck
  }
}
</script>

<style lang="scss" scoped>
.container {
  width: 100%;
  height: 100%;
  background-color: #fff;
  overflow: auto;
}

.container .show {
  display: block;
  background: #F7F8FA;
}

.content {
  display: flex;
  width: 100%;
  height: calc(100vh - 150px);
  overflow: auto;
}

.right {
  position: relative;
  display: block;
  flex: 1;
  height: 100%;
  text-align: left;
  overflow: auto;
  box-sizing: border-box;
  padding: 8px;
  border-left: 1px solid #eee;
}

.cardList {
  display: none;
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: auto;
}

.shop-list {
  width: 98%;
  margin: 0 auto;
}

.filterView {
  text-align: left;
  padding: 10px 13px;

  b {
    display: block;
    font-size: 15px;
    margin-top: 20px;
  }

  .input-view {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 0px;

    .input-block {
      width: 120px;
      height: 40px;
      background: #F3F4F6;

      input {
        width: 100%;
        height: 100%;
        text-align: center;
        line-height: 40px;
        outline: none;
        border: none;
        background: none;
        font-size: 14px;
      }
    }

    .line {
      width: 20px;
      height: 1px;
      border-top: 1px solid #000;
    }
  }
}
</style>
